<template>
  <div class="wrap">
    <ElBacktop target=".form-scroller" :bottom="50">
      <div
        class="el-icon-top"
        title="返回顶部"
        style="
          width: 100%;
          height: 100%;
          color: #1989fa;
          line-height: 40px;
          text-align: center;
          background-color: #f2f5f6;
          box-shadow: 0 0 6px rgba(0, 0, 0, 0.12);
        "></div>
    </ElBacktop>
    <FormView
      v-model="entity"
      :title="entity.id ? '修改资产信息' : '新建资产信息'"
      :toolbar-attrs="{ buttons: ['back', 'save', 'cancel'] }"
      :toolbar-listeners="{ save: persist }">
      <FormHolder ref="form" label-width="110px" :model="entity">
        <FormItemGroup block-title="资产信息">
          <FormInput
            v-model="entity.parentName"
            prop="parentName"
            placeholder="请选择父资产"
            readonly
            label="父资产名称">
            <template #append>
              <ElButton type="button" style="padding-right: 10px" @click="isPickerShow = true">选择</ElButton>
            </template>
          </FormInput>
          <FormTreeSelect
            v-model="entity.belongdeptId"
            :span="12"
            label="所属单位"
            :options="deptTreeList"
            prop="belongdeptId" />
          <FormItem label="房间名称" :span="12" prop="houseId" label-width="110px">
            <VueTreeSelect
              v-model="entity.houseId"
              :options="houseTreeList"
              :disable-branch-nodes="true"
              :class="['form-tree-select', { 'is-readonly': false }]"
              :show-count="true"
              :normalizer="normalizer"
              no-options-text="无房屋选项"
              placeholder="请选择房屋"
              @select="onHouseNodeClick" />
          </FormItem>
          <FormSelect
            v-model="entity.locationId"
            label="存放地点"
            filterable
            :options="positionList"
            value="value"
            prop="locationId" />
          <FormInput
            v-model="entity.parentStorageplace"
            :span="24"
            prop="parentStorageplace"
            max-length="255"
            label="存放全名称" />
        </FormItemGroup>
        <FormItemGroup :gutter="0" block-title="基本信息">
          <FormInput v-model="entity.sauName" prop="sauName" placeholder="请选择标准型号" readonly label="标准型号">
            <template #append>
              <ElButton type="button" style="padding-right: 10px" @click="isShowCtiPicker = true">选择</ElButton>
            </template>
          </FormInput>
          <FormTreeSelect v-model="entity.ctiId" label="资产类别" :options="ctiTreeList" prop="ctiId" required />
          <FormInput
            v-model="entity.number"
            prop="number"
            label="资产编码"
            required
            max-length="64"
            :rules="validateNumber" />
          <FormInput v-model="entity.name" prop="name" label="资产名称" max-length="255" required />
          <FormInput v-model="entity.enName" prop="enName" label="英文名称" max-length="255" />
          <FormInput v-model="entity.alias" prop="alias" label="资产别名" max-length="255" />
          <FormInput v-model="entity.model" prop="model" label="规格型号" max-length="255" required />
          <FormInput v-model="entity.unit" prop="unit" label="计量单位" max-length="64" required />
          <FormInput v-model="entity.sn" prop="sn" label="SN号" max-length="64" />
          <FormInput v-model="entity.voucherNo" prop="voucherNo" label="会计凭证号" max-length="64" />
          <FormTreeSelect v-model="entity.usedeptId" label="使用单位" :options="deptTreeList" prop="usedeptId" />
          <FormTreeSelect v-model="entity.contractId" prop="contractId" :options="contractTreeList" label="合同号" />
          <FormInput v-model="entity.useName" prop="useName" label="使用人" readonly placeholder="请选择使用人">
            <template #append>
              <ElButton type="button" style="padding-right: 10px" @click="isShowUserPicker = true">选择</ElButton>
            </template>
          </FormInput>
          <FormInputNumber
            v-model="entity.originalAmount"
            prop="originalAmount"
            label="原值"
            :min="0"
            :max="999999999"
            required />
          <FormInputNumber v-model="entity.depreciation" prop="depreciation" label="累计折旧" />
          <FormInputNumber v-model="entity.amount" prop="amount" label="金额" :min="0" :max="999999999" />
          <FormSelect
            v-model="entity.monetaryUnit"
            prop="monetaryUnit"
            label="货币单位"
            dict-type="asset_currency_unit" />
          <FormSelect v-model="entity.status" prop="status" label="资产状态" dict-type="asset_status" required />
        </FormItemGroup>
        <FormItemGroup :gutter="2" block-title="供应商信息">
          <FormTreeSelect v-model="entity.makerId" label="生 产 厂" :options="msupplierTreeList" prop="makerId" />
          <FormTreeSelect v-model="entity.supplierId" label="供 应 商" :options="vsupplierTreeList" prop="supplierId" />
          <FormInput v-model="entity.supplierUser" prop="supplierUser" label="联系人" />
          <FormInputPhoneNumber v-model="entity.supplierPhone" prop="supplierPhone" label="联系电话" max-length="11" />
          <FormInput v-model="entity.brand" prop="brand" label="品牌" max-length="255" />
          <FormDatePicker v-model="entity.maintenanceDate" label="维保到期" prop="maintenanceDate" />
          <FormDatePicker v-model="entity.guaranteeDate" label="截止日期" prop="guaranteeDate" />
          <FormTextarea
            v-model="entity.maintenanceInfo"
            prop="maintenanceInfo"
            rows="5"
            label="维保说明"
            max-length="3000" />
        </FormItemGroup>
        <FormItemGroup :gutter="3" block-title="生命周期时间">
          <FormDatePicker v-model="entity.factoryDate" label="出厂日期" prop="factoryDate" />
          <FormSelect v-model="entity.source" prop="source" dict-type="asset_source" label="来源" />
          <FormDatePicker v-model="entity.buyDate" label="购入日期" prop="buyDate" required />
          <FormDatePicker v-model="entity.recordDate" label="建档日期" prop="recordDate" />
          <FormDatePicker v-model="entity.acquireDate" label="取得日期" prop="acquireDate" />
          <FormDatePicker v-model="entity.useDate" label="使用日期" prop="useDate" />
          <FormInputNumber v-model="entity.usefulLife" prop="usefulLife" label="使用期限" required />
          <FormDatePicker v-model="entity.scrapDate" label="报废日期" prop="scrapDate" />
        </FormItemGroup>
        <FormItemGroup :gutter="4" block-title="其它信息">
          <FormInput v-model="entity.fundsSource" prop="fundsSource" :span="24" max-length="255" label="经费来源" />
          <FormRadioGroup
            v-model="entity.fixedAssets"
            label="固定资产"
            required
            prop="fixedAssets"
            classic
            radio-type="radio"
            :options="[
              { label: '否', value: '0' },
              { label: '是', value: '1' }
            ]" />
          <FormSelect
            v-model="entity.purchaseMode"
            prop="purchaseMode"
            label="采购方式"
            dict-type="asset_purchase_method" />
          <FormSelect v-model="entity.usageOption" prop="usageOption" label="使用方式" dict-type="asset_how_user" />
          <FormInput v-model="entity.acquireWay" prop="acquireWay" label="取得方式" max-length="255" />
          <FormTextarea v-model="entity.description" prop="description" rows="5" label="功能描述" max-length="3000" />
          <FormTextarea v-model="entity.remarks" prop="remarks" label="备注" rows="5" max-length="3000" />

          <FormInput v-model="entity.photo" :span="24" label="照片">
            <template #default>
              <UploadAvatar
                v-if="entity.unid"
                ref="uploadAvatar"
                :limit="1"
                :data="{ uniqueCode: entity.unid, photo: entity.photo, model: 'asset', classify: 'card' }"
                @uploadDel="uploadDel"
                @uploadSuccess="uploadSuccess" />
            </template>
          </FormInput>
        </FormItemGroup>
      </FormHolder>
      <!-- 选择用户 -->
      <UserPicker
        v-if="isShowUserPicker"
        :reserve-position-on-close="false"
        close-on-click-modal
        :visible.sync="isShowUserPicker"
        @confirm="onConfirmUser" />
      <!-- 标准型号 -->
      <AssetSauTable :visible.sync="isShowCtiPicker" in-type="ALL" :multiple="false" @confirm="onConfirm" />

      <AssetCardTable
        :visible.sync="isPickerShow"
        :asset-card-id="entity.id"
        in-type="ALL"
        :multiple="false"
        @confirm="onCardConfirm" />
    </FormView>
  </div>
</template>

<script>
  import { addObj, putObj, getObj, createAssetCard } from '@/api/asset/fyassetassetcard'
  import { getPositionListByHouseId } from '@/api/space/fyroomposition'
  import { getHouseTree } from '@/api/space/fyroomhouse'
  import { fetchCtiTree } from '@/api/asset/fyassetcti'
  import { contractTree } from '@/api/asset/fyassetcontract'
  import { supplierTree } from '@/api/asset/fyassetsupplier'
  import form from '@/vue/mixin/form'
  import { fetchTree } from '@/api/admin/dept'

  export default {
    name: 'CardForm',
    relativeViewId: 'CardView',
    mixins: [form],
    data() {
      const validateNumber = (rule, value, callback) => {
        if (value !== '') {
          // const reg = /[\u4e00-\u9fa5]/g
          const reg = /^[a-zA-Z0-9_|.|-]+$/
          if (!reg.test(value)) {
            callback(new Error('资产编码只能包含数字、字母、下线划、中线划和小数点'))
          } else {
            callback()
          }
        } else {
          callback()
        }
      }

      return {
        entity: {
          id: null,
          tenantId: null,
          deptId: null,
          deptFullname: null,
          createBy: null,
          createId: null,
          createTime: null,
          updateBy: null,
          updateTime: null,
          delFlag: null,
          unid: '',
          parentId: null,
          parentName: null,
          parentNumber: null,
          parentUseunitname: null,
          parentStorageplace: null,
          sauName: null,
          sauId: null,
          ctiId: null,
          ctiName: null,
          ctiType: null,
          classified: null,
          classifiedCode: null,
          number: null,
          name: '',
          enName: null,
          alias: null,
          model: '',
          unit: '',
          sn: null,
          voucherNo: null,
          belongdept: '广州海洋地质调查局',
          belongdeptFullname: '广州海洋地质调查局',
          belongdeptId: '254',
          usedept: '广州海洋地质调查局',
          usedeptFullname: '广州海洋地质调查局',
          usedeptId: '254',
          useName: 'liyue',
          useId: '1187',
          location: null,
          locationId: null,
          locationType: null,
          houseId: null,
          houseName: null,
          source: '01',
          contractNumber: null,
          contractId: null,
          originalAmount: 0,
          depreciation: null,
          amount: null,
          monetaryUnit: '人民币',
          status: '0',
          maker: null,
          makerId: null,
          supplier: null,
          supplierId: null,
          supplierUser: null,
          supplierPhone: null,
          brand: null,
          maintenanceDate: null,
          maintenanceInfo: null,
          guaranteeDate: null,
          factoryDate: null,
          buyDate: '2023-05-12',
          recordDate: null,
          acquireDate: null,
          useDate: null,
          usefulLife: null,
          scrapDate: null,
          fundsSource: null,
          purchaseMode: null,
          fixedAssets: '1',
          acquireWay: null,
          usageOption: null,
          photo: null,
          description: null,
          remarks: null,
          price: null,
          barcode: null
        },
        deptTreeList: [],
        positionList: [],
        houseTreeList: [],
        ctiTreeList: [],
        contractTreeList: [],
        msupplierTreeList: [],
        vsupplierTreeList: [],
        isShowUserPicker: false,
        isShowCtiPicker: false,
        isPickerShow: false,
        validateNumber: [{ validator: validateNumber, trigger: 'blur' }]
      }
    },
    created() {
      this.init()
    },
    methods: {
      create: createAssetCard,
      load: getObj,
      save: addObj,
      update: putObj,
      async init() {
        const res = await fetchTree()
        this.deptTreeList = res.data.data

        const houseRes = await getHouseTree()
        this.houseTreeList = houseRes.data.data

        const ctiRes = await fetchCtiTree()
        this.ctiTreeList = ctiRes.data.data

        const contractRes = await contractTree()
        this.contractTreeList = contractRes.data.data

        // 供应商
        const vsupplierRes = await supplierTree('V')
        this.vsupplierTreeList = vsupplierRes.data.data

        // 厂商
        const msupplierRes = await supplierTree('M')
        this.msupplierTreeList = msupplierRes.data.data

        // 加载存放地点
        if (this.entity.houseId) {
          await this.loadPositionList(this.entity.houseId)
        }
      },
      onConfirmUser(users) {
        const user = users[0]
        this.entity.useId = user.id
        this.entity.useName = user.name
        this.entity.usedeptId = user.deptId
        this.entity.usedept = user.deptName
        this.entity.usedeptFullname = user.deptFullname
      },
      onConfirm(rows) {
        // console.log(rows)
        if (rows) {
          const row = rows[0]
          this.entity.sauId = row.id
          this.entity.sauName = row.name
          this.entity.name = row.name
          this.entity.amount = row.amount
          this.entity.unit = row.unit
          this.entity.model = row.model
          this.entity.barcode = row.barcode

          this.entity.ctiId = row.ctiId
          this.entity.ctiName = row.ctiName
          this.entity.classified = row.ctiFullName
          this.entity.classifiedCode = row.ctiFullCode
          this.entity.ctiType = row.assetType
        }
      },
      normalizer(node) {
        if (node.children && !node.children.length) {
          delete node.children
        }
        return {
          id: node.idCard,
          label: node.name,
          isDisabled: this.$isBlank(node.children) && !(node.affiliName === 'HOUSE'),
          children: node.children
        }
      },
      async onHouseNodeClick(node) {
        await this.loadPositionList(node.idCard)
      },
      async loadPositionList(houseId) {
        const res = await getPositionListByHouseId({ houseId })
        this.positionList = res.data.data
      },
      uploadDel() {
        this.entity.picture = ''
      },
      uploadSuccess(file) {
        this.entity.picture = file.url
      },
      onCardConfirm(rows) {
        const row = rows[0]
        this.entity.parentId = row.id
        this.entity.parentName = row.name
      }
    }
  }
</script>

<style>
  .wrap {
    height: 100%;
    overflow-x: hidden;
  }
</style>
